package com.weather.common.utils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.Reader;
import java.io.StringReader;

/**
 * @author: htc
 * @date: Created in 16:57 2018/5/4.
 */
public class XmlBuilder {
    /**
     * 将xml转化为对象
     *
     * @param clazz 返回的对象类型
     * @param xmlStr 二进制字符流
     * @return
     */
    public static Object xml2Obj(Class<?> clazz, String xmlStr) throws Exception {
        Object xmlObject = null;
        Reader reader = null;

        JAXBContext context = JAXBContext.newInstance(clazz);
        //Unmarshaller 可以将XML解析为对象
        Unmarshaller unmarshaller = context.createUnmarshaller();
        reader = new StringReader(xmlStr);
        //解析
        xmlObject = unmarshaller.unmarshal(reader);
        if (null != reader) {
            reader.close();
        }
        return xmlObject;
    }
}
